<template>
  <el-dialog
    v-model="visible"
    title="导入字段配置"
    width="80%"
    :before-close="handleClose"
  >
    <div class="field-config-importer">
      <!-- JSON输入区域 -->
      <el-card class="json-input-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>字段配置JSON</span>
            <div class="header-actions">
              <el-button size="small" @click="clearInput">清空</el-button>
              <el-button size="small" type="primary" @click="formatJson">格式化</el-button>
            </div>
          </div>
        </template>
        
        <el-input
          v-model="jsonInput"
          type="textarea"
          :rows="12"
          placeholder="请粘贴字段配置JSON数据..."
          class="json-textarea"
        />
        
        <div class="input-actions">
          <el-button type="primary" @click="parseJson" :loading="parsing">解析配置</el-button>
          <el-button @click="loadSampleData">加载示例数据</el-button>
        </div>
      </el-card>
      
      <!-- 解析结果 -->
      <el-card v-if="parseResult" class="result-card" shadow="never">
        <template #header>
          <span>解析结果</span>
        </template>
        
        <div v-if="parseResult.success" class="success-result">
          <el-alert
            title="解析成功"
            type="success"
            :closable="false"
            show-icon
          />
          
          <!-- 预览信息 -->
          <div class="preview-info">
            <el-descriptions title="字段配置概览" :column="2" border>
              <el-descriptions-item label="总字段数">
                {{ preview.totalFields }}
              </el-descriptions-item>
              <el-descriptions-item label="主键字段">
                <el-tag v-for="key in preview.primaryKeys" :key="key" size="small" class="field-tag">
                  {{ key }}
                </el-tag>
                <span v-if="preview.primaryKeys.length === 0" class="empty-text">无</span>
              </el-descriptions-item>
              <el-descriptions-item label="自增字段">
                <el-tag v-for="field in preview.autoIncrementFields" :key="field" size="small" type="warning" class="field-tag">
                  {{ field }}
                </el-tag>
                <span v-if="preview.autoIncrementFields.length === 0" class="empty-text">无</span>
              </el-descriptions-item>
              <el-descriptions-item label="列表显示字段">
                <el-tag v-for="field in preview.listFields.slice(0, 5)" :key="field" size="small" type="info" class="field-tag">
                  {{ field }}
                </el-tag>
                <span v-if="preview.listFields.length > 5" class="more-text">
                  等{{ preview.listFields.length }}个字段
                </span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          
          <!-- 字段列表预览 -->
          <div class="field-list-preview">
            <h4>字段列表预览</h4>
            <el-table :data="parseResult.data" border max-height="300" size="small">
              <el-table-column prop="columnName" label="字段名" width="120" />
              <el-table-column prop="columnType" label="类型" width="100" />
              <el-table-column prop="columnComment" label="注释" width="150" />
              <el-table-column prop="javaFieldName" label="Java字段名" width="120" />
              <el-table-column prop="javaFieldType" label="Java类型" width="100" />
              <el-table-column label="选项" width="200">
                <template #default="{ row }">
                  <el-tag v-if="row.isPrimaryKey" size="small" type="danger">主键</el-tag>
                  <el-tag v-if="row.isAutoIncrement" size="small" type="warning">自增</el-tag>
                  <el-tag v-if="row.showInList" size="small" type="info">列表</el-tag>
                  <el-tag v-if="row.showInForm" size="small" type="success">表单</el-tag>
                  <el-tag v-if="row.showInQuery" size="small">查询</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <div v-else class="error-result">
          <el-alert
            :title="parseResult.error"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmImport" 
          :disabled="!parseResult?.success"
        >
          确认导入
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue'
import {ElMessage} from 'element-plus'
import type {CodegenColumnDTO} from '@/api/codegen'
import {type BackendFieldConfig, generateFieldPreview, parseFieldConfigFromJson} from '@/utils/fieldConfigParser'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'import', data: CodegenColumnDTO[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const jsonInput = ref('')
const parsing = ref(false)
const parseResult = ref<{
  success: boolean
  data?: CodegenColumnDTO[]
  error?: string
} | null>(null)

const preview = computed(() => {
  if (!parseResult.value?.success || !parseResult.value.data) {
    return {
      totalFields: 0,
      primaryKeys: [],
      autoIncrementFields: [],
      listFields: [],
      formFields: [],
      queryFields: []
    }
  }
  
  // 将前端格式转换为后台格式以生成预览
  const backendFormat: BackendFieldConfig[] = parseResult.value.data.map(field => ({
    columnName: field.columnName,
    columnType: field.columnType,
    columnLength: field.columnLength,
    columnScale: field.columnScale,
    columnComment: field.columnComment,
    isPrimaryKey: field.isPrimaryKey,
    isAutoIncrement: field.isAutoIncrement,
    isNullable: field.isNullable,
    defaultValue: field.defaultValue || null,
    javaFieldName: field.javaFieldName,
    javaFieldType: field.javaFieldType,
    showInList: field.showInList,
    showInForm: field.showInForm,
    showInQuery: field.showInQuery,
    queryType: field.queryType,
    formType: field.formType,
    onUpdateCurrentTimestamp: field.onUpdateCurrentTimestamp,
    extra: field.extra || null
  }))
  
  return generateFieldPreview(backendFormat)
})

const clearInput = () => {
  jsonInput.value = ''
  parseResult.value = null
}

const formatJson = () => {
  try {
    const parsed = JSON.parse(jsonInput.value)
    jsonInput.value = JSON.stringify(parsed, null, 2)
    ElMessage.success('JSON格式化成功')
  } catch (error) {
    ElMessage.error('JSON格式错误，无法格式化')
  }
}

const parseJson = () => {
  if (!jsonInput.value.trim()) {
    ElMessage.warning('请输入字段配置JSON')
    return
  }
  
  parsing.value = true
  
  try {
    parseResult.value = parseFieldConfigFromJson(jsonInput.value)
    
    if (parseResult.value.success) {
      ElMessage.success('字段配置解析成功')
    } else {
      ElMessage.error('字段配置解析失败')
    }
  } catch (error) {
    parseResult.value = {
      success: false,
      error: `解析失败: ${error instanceof Error ? error.message : '未知错误'}`
    }
    ElMessage.error('字段配置解析失败')
  } finally {
    parsing.value = false
  }
}

const loadSampleData = () => {
  const sampleData = [
    {
      "columnName": "id",
      "columnType": "BIGINT",
      "columnLength": 19,
      "columnScale": 0,
      "columnComment": "主键",
      "isPrimaryKey": true,
      "isAutoIncrement": false,
      "isNullable": false,
      "defaultValue": null,
      "javaFieldName": "id",
      "javaFieldType": "Long",
      "showInList": false,
      "showInForm": false,
      "showInQuery": false,
      "queryType": "=",
      "formType": "number",
      "onUpdateCurrentTimestamp": false,
      "extra": null
    },
    {
      "columnName": "username",
      "columnType": "VARCHAR",
      "columnLength": 50,
      "columnScale": 0,
      "columnComment": "用户名",
      "isPrimaryKey": false,
      "isAutoIncrement": false,
      "isNullable": false,
      "defaultValue": null,
      "javaFieldName": "username",
      "javaFieldType": "String",
      "showInList": true,
      "showInForm": true,
      "showInQuery": true,
      "queryType": "LIKE",
      "formType": "input",
      "onUpdateCurrentTimestamp": false,
      "extra": null
    }
  ]
  
  jsonInput.value = JSON.stringify(sampleData, null, 2)
  ElMessage.success('示例数据已加载')
}

const confirmImport = () => {
  if (parseResult.value?.success && parseResult.value.data) {
    emit('import', parseResult.value.data)
    handleClose()
    ElMessage.success(`成功导入 ${parseResult.value.data.length} 个字段配置`)
  }
}

const handleClose = () => {
  visible.value = false
  // 清理数据
  setTimeout(() => {
    jsonInput.value = ''
    parseResult.value = null
  }, 300)
}
</script>

<style scoped>
.field-config-importer {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.json-input-card {
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.json-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.input-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
}

.result-card {
  margin-top: 16px;
}

.success-result {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-info {
  margin-top: 16px;
}

.field-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.empty-text {
  color: #909399;
  font-style: italic;
}

.more-text {
  color: #606266;
  font-size: 12px;
}

.field-list-preview {
  margin-top: 16px;
}

.field-list-preview h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.error-result {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>